package mailer;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;

/**
 * 邮件发送工具实现类
 * Created at 2015/9/22 22:25
 *
 * @author young
 * @version 1.0.0
 */
public class MailUtil {
	protected final Logger logger = Logger.getLogger(getClass());

	public boolean send(Mail mail) {
		// 发送email
		HtmlEmail email = new HtmlEmail();
		try {
			email.setHostName(mail.getHost());
			email.setCharset(Mail.ENCODEING);
			email.addTo(mail.getReceiver());
			for (String cc : mail.getCc()){
				email.addCc(cc);
			}
			email.setFrom(mail.getSender(), mail.getName());
			email.setAuthentication(mail.getUsername(), mail.getPassword());
			email.setSubject(mail.getSubject());
			email.setMsg(mail.getMessage());
			email.send();
			logger.debug(mail.getSender() + " 发送邮件到 " + mail.getReceiver());
			return true;
		} catch (EmailException e) {
			e.printStackTrace();
			logger.info(mail.getSender() + " 发送邮件到 " + mail.getReceiver() + " 失败");
			return false;
		}
	}

	public static void main(String[] args) {
		Mail mail = new Mail();
		mail.setHost("smtp.163.com");
		mail.setSender("xxxxxxxxx@163.com");
		mail.setReceiver("xxxxxx@qq.com");
		List<String> ccList = new ArrayList<String>();
		ccList.add("xxxxxxxxxx@gmail.com");
		mail.setCc(ccList);
		mail.setUsername("xxxxxxxxx@163.com");
		mail.setPassword("xxxxxxx");
		mail.setSubject("[1200606]DM100089-账户余额不足");
		StringBuilder builder = new StringBuilder();
		builder.append("渠道号:1200606\n");
		builder.append("错误码:DM100089\n");
		builder.append("错误信息:账户余额不足\n");
		mail.setMessage(builder.toString());
		new MailUtil().send(mail);
	}
}
